import EventRoute from './EventRoute'
import { API, EventData } from './type'

export default class EventRouter {
  #api: API = {} as API
  #routers: Map<string, EventRoute[]>

  constructor() {
    this.#routers = new Map()
  }

  //添加单个路由
  addRoute(route: EventRoute) {
    const routes = this.#routers.get(route.type as string)

    if (routes) {
      routes.push(route)
    } else {
      this.#routers.set(route.type as string, [route])
    }

    return this
  }

  //添加多个路由
  addRoutes(routers: EventRoute[]) {
    routers.forEach((route) => this.addRoute(route))

    return this
  }

  removeRoute(event: string, type: string) {
    const removeInRoutes = (routes: EventRoute[] | undefined, event: string) => {
      const position = routes?.findIndex((route) => route.event === event)
      position && position >= 0 && routes?.splice(position, 1)
    }
    if (type) {
      const routes = this.#routers.get(type)
      removeInRoutes(routes, event)
    } else {
      this.#routers.forEach((routes) => removeInRoutes(routes, event))
    }

    return this
  }

  //触发指定名称的路由回调
  router(data: EventData) {
    const { type, event } = data

    const triggerInRoutes = (routes: EventRoute[] | undefined, event: string) => {
      const route = routes?.find((route) => route.event === event)
      route?.callback(this.#api, data.data)
    }

    if (type) {
      const routes = this.#routers.get(type)
      triggerInRoutes(routes, event)
    } else {
      this.#routers.forEach((routes) => triggerInRoutes(routes, event))
    }

    return this
  }

  //添加api
  addApi<T extends keyof API>(key: T, api: API[T]) {
    this.#api[key] = api
    return this
  }
}
